package com.ctg.itrdc.imageconsole.data.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.constants.DockerConstant;
import com.ctg.itrdc.imageconsole.data.dao.IDockerMicroImageDao;
import com.ctg.itrdc.imageconsole.data.entity.DockerMicroImage;
import com.ctg.itrdc.paspsdk.common.entity.PageInfo;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;
import com.ctg.itrdc.paspsdk.data.dao.impl.BaseDaoImpl;

@Component("dockerMicroImageDao")
public class DockerMicroImageDaoImpl extends BaseDaoImpl implements IDockerMicroImageDao {

	@Override
	public PageInfo<DockerMicroImage> queryBuildList(DockerMicroImage dockerMicroImage, Integer pageNum,
			Integer pageSize, Boolean isDockerManager) {
		String sql = "select dmi.*,dmu.code as create_user_code from docker_micro_image dmi , docker_micro_user dmu"
				+ " where dmi.last_update_user_id=dmu.sys_user_id ";
		StringBuilder sqlSb = new StringBuilder(sql);
		
		List<Object> params = new ArrayList<Object>();
		if (dockerMicroImage.getId() != null) {
			sqlSb.append(" and dmi.id = ?");
			params.add(dockerMicroImage.getId());
		}
		if (StringUtils.isNotEmpty(dockerMicroImage.getImageName())) {
			sqlSb.append(" and dmi.image_name like ?");
			params.add("%" + dockerMicroImage.getImageName() + "%");
		}
		if (StringUtils.isNotEmpty(dockerMicroImage.getTag())) {
			sqlSb.append(" and dmi.tag = ?");
			params.add(dockerMicroImage.getTag());
		}
		if (StringUtils.isNotEmpty(dockerMicroImage.getBuildImageStatus())) {
			sqlSb.append(" and dmi.build_image_status = ?");
			params.add(dockerMicroImage.getBuildImageStatus());
		}
		if (!isDockerManager) {
			sqlSb.append(" and dmi.create_user_id = ?");
			params.add(dockerMicroImage.getCreateUserId());
		}
		sqlSb.append(" order by dmi.create_time desc");
		return this.jdbcFindPageInfo(sqlSb.toString(), DockerMicroImage.class, params, pageNum, pageSize, false);
	}

	@Override
	public DockerMicroImage selectById(Long id) {
		DockerMicroImage dockerMicroImage = new DockerMicroImage();
		dockerMicroImage.setId(id);
		return super.selectByPrimaryKey(dockerMicroImage);
	}


	@Override
	public List<DockerMicroImage> isVersionExist(Long userId, String imageName, String tag) {
		String sql = "select * from docker_micro_image where create_user_id = ? and image_name = ? and tag = ? and build_image_status != ?";
		List<Object> params = new ArrayList<>();
		params.add(userId);
		params.add(imageName);
		params.add(tag);
		params.add(DockerConstant.DockerMicroImageCons.BUILD_FAIL);
		
		return super.jdbcFindList(sql, DockerMicroImage.class, params);
	}

	@Override
	public void deleteById(Long id) {
		DockerMicroImage microImage = new DockerMicroImage();
		microImage.setId(id);
		super.deleteByPrimaryKey(microImage);
		
		String sql = "delete from docker_micro_image_content where docker_micro_image_id = ?";
		
		super.getJdbcTemplate().update(sql, id);
	}

}
